package com.wxy.netty.黏包半包处理;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.Scanner;

/**
 * @author 47868
 */
public class Client4 {
    private static final Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Channel channel = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        socketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) {
                                int count = 1;
                                ByteBuf buf =ctx.alloc().buffer();
                                while (true) {
                                    String message = scanner.nextLine();
                                    if ("exit".equals(message)) {
                                        if (buf.readableBytes()>0){
                                            ctx.writeAndFlush(buf); //会自动释放buf
                                        }
                                        ctx.close();
                                        break;
                                    }
                                    buf.writeInt(message.length());
                                    buf.writeByte(1);
                                    buf.writeBytes(message.getBytes());
                                    count++;
                                    if(count > 3){
                                        ctx.writeAndFlush(buf);
                                        buf=ctx.alloc().buffer();
                                        count = 1;
                                    }
                                }
                            }
                        });
                    }
                }).connect("127.0.0.1",8888).sync().channel();
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                eventLoopGroup.shutdownGracefully();
            }
        });
    }
}
